package com.velvetantler.weather.utils

import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import com.velvetantler.weather.bean.CityStar

object CityStarUtils {

    private var sharedPreferences: SharedPreferences? = null

    fun init(context: Context) {
        sharedPreferences = context.getSharedPreferences("city_star", Context.MODE_PRIVATE)
    }

    /**
     * 添加城市收藏
     */
    fun addCityStar(city: CityStar) {
        val cityJson = Gson().toJson(city)
        sharedPreferences?.edit()?.putString(city.cityName, cityJson)?.apply()
    }

    /**
     * 获取收藏的城市列表
     */
    fun getCityStarList(): List<CityStar> {
        val cityStarList = mutableListOf<CityStar>()
        sharedPreferences?.all?.values?.forEach {
            val city = Gson().fromJson(it.toString(), CityStar::class.java)
            cityStarList.add(city)
        }
        return cityStarList
    }

    /**
     * 获取当前城市
     */
    fun getCurrentCity(cityName: String): Boolean {
        val cityJson = sharedPreferences?.getString(cityName, null)
        return !cityJson.isNullOrEmpty()
    }

    /**
     * 移除收藏
     */
    fun removeCityStar(cityName: String) {
        sharedPreferences?.edit()?.remove(cityName)?.apply()
    }
}